package com.dj.mingkong.portal.biz.service.music.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.common.constant.RedisConstants;
import com.dj.mingkong.common.exception.ValidateException;
import com.dj.mingkong.common.infrastructure.eo.database.music.AlbumEo;
import com.dj.mingkong.common.infrastructure.eo.database.music.AlbumLikeEo;
import com.dj.mingkong.common.microservice.UserContext;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.portal.biz.controller.music.vo.request.AlbumLikeAddVo;
import com.dj.mingkong.portal.biz.controller.music.vo.request.AlbumLikeQueryVo;
import com.dj.mingkong.portal.biz.controller.music.vo.response.AlbumLikeVo;
import com.dj.mingkong.portal.biz.repository.database.music.AlbumLikeRepository;
import com.dj.mingkong.portal.biz.repository.database.music.AlbumRepository;
import com.dj.mingkong.portal.biz.service.music.AlbumLikeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * 专辑点赞服务
 *
 * @author zenglonghui
 * @date: 2023/2/3 15:20
 */
@Slf4j
@Service("albumLikeService")
public class AlbumLikeServiceImpl implements AlbumLikeService {
    @Resource
    private AlbumLikeRepository albumLikeRepository;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private AlbumRepository albumRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(AlbumLikeAddVo addVo) {
        final String key = RedisConstants.ALBUM_LIKE.concat(UserContext.getUserId().toString())
                .concat(RedisConstants.KEY_SPLIT).concat(addVo.getAlbumId().toString());
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            throw new ValidateException("24小时内不允许重复点赞！");
        }
        final AlbumEo albumEo = albumRepository.getById(addVo.getAlbumId());
        AssertUtils.isNotNull(albumEo, "albumId invalid");
        final AlbumLikeEo albumLikeEo = AlbumLikeEo.builder().albumId(addVo.getAlbumId())
                .userId(UserContext.getUserId()).build();
        albumLikeRepository.save(albumLikeEo);
        albumRepository.updateById(albumEo.setLikeCount(albumEo.getLikeCount() + 1));
        redisTemplate.opsForValue().set(key, RedisConstants.ALBUM_LIKE, 1, TimeUnit.DAYS);
    }

    @Override
    public Page<AlbumLikeVo> pageByVo(AlbumLikeQueryVo queryVo) {
        return albumLikeRepository.getMapper().listPage(Page.of(queryVo.getPage(), queryVo.getPageSize()), queryVo);
    }
}
